package light.im.loginserver.domain.msg;

import java.util.Date;
import java.util.List;

import service.LoginService;

import light.im.IMSession;
import light.im.loginserver.domain.model.Client;
import light.im.loginserver.domain.model.Message;

public class MessageService {

	MessageStore msgStore = new MessageStore();
	private MessageService(){}
	private static MessageService instance = new MessageService();
	public static MessageService getInstance(){
		return instance;
	}
	
	public void sendTo(IMSession session, String from, String to, String msg)
	{
		Message m = new Message();
		m.setFrom(from);
		m.setContent(msg);
		m.setTo(to);
		//m.setSenderIP(session.getIoSession().getRemoteAddress().toString());
		m.setSendTime(new Date().getTime());
		LoginService ls = LoginService.getInstance();
		Client cl = ls.isLogin(to);
		if(cl==null)
		{
			msgStore.persistMessage(m);
		}
		else
		{
			msgStore.bufferMessage(m);
		}
	}
	
	public List<Message> consumeImediaMessages(IMSession session, String targetUser)
	{
		List<Message> l = msgStore.consumeBufferMsgByTarget(targetUser);
		if(l==null || l.size()==0)
			return null;
		for(Message m:l)
		{
			//m.setRecverIP(session.getIoSession().getRemoteAddress().toString());
			m.setRecvTime(new Date().getTime());
		}
		return l;
	}
	
	public List<Message> consumeHistoryMessages(IMSession session, String targetUser)
	{
		List<Message> l = msgStore.consumePersistMsgByTarget(targetUser);
		if(l==null || l.size()==0)
			return null;
		for(Message m:l)
		{
			//m.setRecverIP(session.getIoSession().getRemoteAddress().toString());
			m.setRecvTime(new Date().getTime());
		}
		return l;
	}
	
	
}
